/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include <stdlib.h>
#include <string.h>

extern "C" char *flt(char *str, double num, int size, int precision, char fmt, int flags) {
	char tmp[80];
	char c, sign;
	int n, i;
	if (flags & LEFT) {
		flags &= ~ZEROPAD;
	}
	c = (flags & ZEROPAD) ? '0' : ' ';
	sign = 0;
	if (flags & SIGN) {
		if (num < 0.0) {
			sign = '-';
			num = -num;
			size--;
		} else if (flags & PLUS) {
			sign = '+';
			size--;
		} else if (flags & SPACE) {
			sign = ' ';
			size--;
		}
	}
	if (precision < 0) {
		precision = 6;
	} else if (precision == 0 && fmt == 'g') {
		precision = 1;
	}
	cfltcvt(num, tmp, fmt, precision);
	if ((flags & SPECIAL) && precision == 0) {
		forcdecpt(tmp);
	}
	if (fmt == 'g' && !(flags & SPECIAL)) {
		cropzeros(tmp);
	}
	n = strlen(tmp);
	size -= n;
	if (!(flags & (ZEROPAD | LEFT))) {
		while (size-- > 0) {
			*str++ = ' ';
		}
	}
	if (sign) {
		*str++ = sign;
	}
	if (!(flags & LEFT)) {
		while (size-- > 0) {
			*str++ = c;
		}
	}
	for (i = 0; i < n; i++) {
		*str++ = tmp[i];
	}
	while (size-- > 0) {
		*str++ = ' ';
	}
	return str;
}
